package com.itheima.health.service.impl;

import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;


    @Override
    public User findByUsername(String username) {
        //调用DAO查询数据
//        return userDao.selectByUsername(username);
        //判断用户是否存在
        User user = userDao.selectByUsername(username);
        if (user==null){
            //不存在, 返回null
            return null;
        }
            //存在  , 根据userId查用户权限   添加"角色t_role"和"权限t_permission"
        List<Role> roles = roleDao.selectByUserId(user.getId());
        //给List<role> 依次填入permission值
        for (Role role : roles) {
            //根据角色rollId查permission
            List<Permission> permissions = permissionDao.selectByRoleId(role.getId());
            //将permissions数据添加进role
            role.getPermissions().addAll(permissions);
        }
        user.getRoles().addAll(roles);
        return user;
    }
}
